import axios from "axios";
import type { AxiosRequestConfig } from "axios";
import { resReject, resResolve, reqReject, reqResolve } from "./interceptors";

type Result<T> = {
  status: boolean;
  code: number;
  message: string;
  data: T;
};
// 基础配置，url和超时时间
const baseConfig: AxiosRequestConfig = {
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 30000,
  headers: {
    "Content-Type": "application/json",
  },
  withCredentials: true,
};

// 构建Axios实例
const instance = axios.create(baseConfig);
instance.interceptors.request.use(reqResolve, reqReject);
instance.interceptors.response.use(resResolve, resReject);

export const request = {
  // 自定义请求方法
  request: async <T = any>(config: AxiosRequestConfig) => {
    const { data } = await instance.request<Result<T>>(config);
    return data;
  },

  get: <T = any>(url: string, params?: any) => {
    return request.request<T>({ url, method: "get", params });
  },

  post: <T = any>(url: string, data?: any, params?: any) => {
    return request.request<T>({ url, method: "post", data, params });
  },

  put: <T = any>(url: string, data?: any, params?: any) => {
    return request.request<T>({ url, method: "put", data, params });
  },

  delete: <T = any>(url: string, params?: any) => {
    return request.request<T>({ url, method: "delete", params });
  },
};
